<?php

namespace Common\Model;

use Common\Util\LibUtil;
use Think\Model;

class ImageModel extends Model
{
    protected $tableName = 'image';
    //图片文件夹
    public static $image_dir = 'Public/uploads/images/';

    //图片规则
    private $rules = array(
        array('w' => 640, 'h' => 240, 'name' => '_b', 'isCut' => '1'),
        array('w' => 320, 'h' => 320, 'name' => '_m', 'isCut' => '1'),
    );

    /**
     * 将图片上传至指定文件夹
     * @param $userId =0
     * @param array $files
     * @param array $rules
     * @return array $images
     */
    public static function uploadImage($userId = 0, $files = array(), $rules = array())
    {


        if (empty($files)) return false;
        $image_dir = self::$image_dir;  // upload path
        $images = [];

        if (is_string($files["tmp_name"])) $files["tmp_name"] = array($files["tmp_name"]);
        if (is_string($files["name"])) $files["name"] = array($files["name"]);



        foreach ($files["tmp_name"] as $key => $tmp_name) {
            $entry = [
                'user_id' => $userId,
                'name' => isset($files['name'][$key]) ? $files['name'][$key] : ''

            ];

            $userObj = M('image');
            if ($userObj->create($entry, 1)) {
                $status = $userObj->add();
            }



            $imageId = $status;
            $destinationPath = $image_dir . LibUtil::getFacePath($imageId);
            LibUtil::make_dir($destinationPath);//创建目录
            $fileName = $imageId . '_o.jpg'; // 得到文件名
            $ext = self::extend($entry['name']);

            //修改后缀名为jpg
            if ($ext == "jpg") {
                move_uploaded_file($tmp_name, $destinationPath . $fileName);
            } elseif ($ext == "gif") {
                $im = imagecreatefromgif($tmp_name);//Create a new image from file or URL
                ImageJpeg($im, $destinationPath . $fileName);//creates a JPEG file from the given image.
            } elseif ($ext == "png") {
                $im = imagecreatefrompng($tmp_name);
                ImageJpeg($im, $destinationPath . $fileName);
            } elseif ($ext == "jpeg") {
                $im = imagecreatefromjpeg($tmp_name);
                ImageJpeg($im, $destinationPath . $fileName);
            }


            $Image = new ImageModel();
            //检查图片是否存在，存在则赋值$Image
            if (file_exists($destinationPath . $imageId . '_o.jpg')) {
                $rules = !empty($rules);
                try {
                    $Image->creatThumbPi($destinationPath . $imageId . '_o.jpg', $destinationPath, $imageId, $rules);
                } catch (\Exception $e) {
                    //Log::info($e);
                }

                $images[] = array(
                    'image_id' => $imageId,
                    'pic' => LibUtil::getPicUrl($imageId, 3, $image_dir),
                );
            }
        }


        $patient_data['image_id']=$imageId;
        $patient_data['id']=$userId;
        $patient = M('patient');

        if (!$patient->create($patient_data,2)) {
            return false;
        }else{
            $patient->save();
        }
        return $images;
    }

    /**
     * 获取文件的所有元素
     * @param string $file_name "/path/path/name.test"
     * @return array $extend  ['dirname'=>"/path/path",'basename'=>".test",'extension'=>"test",'filename'=>"name"]
     */
    static function extend($file_name)
    {
        $extend = pathinfo($file_name);
        $extend = isset($extend["extension"]) ? strtolower($extend["extension"]) : 'jpg';
        return $extend;
    }

}